/**
 * Copyright (c) 2016-2020, Michael Yang 杨福海 (fuhai999@gmail.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jpress.model;

import com.jfinal.core.JFinal;
import io.jboot.db.annotation.Table;
import io.jboot.utils.StrUtil;
import io.jpress.commons.utils.CommonsUtils;
import io.jpress.model.base.BaseMenu;

/**
 * Generated by Jboot.
 */
@Table(tableName = "menu", primaryKey = "id")
public class Menu extends BaseMenu<Menu> {


    /**
     * header：前台顶部菜单；
     * main:前台主菜单；
     * footer:前台底部菜单；
     */
    public static final String TYPE_HEADER = "header"; //前台的头部菜单
    public static final String TYPE_MAIN = "main"; //前台的主菜单，一般用在左边导航或者右边导航，根据模板本身来决定的
    public static final String TYPE_FOOTER = "footer"; //前台的底部菜单


    private String baseUrl;

    private String getBaseUrl() {
        if (baseUrl == null) {
            baseUrl = CommonsUtils.removeSuffix(getUrl());
        }
        return baseUrl;
    }

    private static String contextPath = JFinal.me().getContextPath();


    public boolean isUrlStartWidth(String url) {

        String baseUrl = getBaseUrl();
        if (StrUtil.isBlank(baseUrl)) {
            return false;
        }

        baseUrl = removeSuffix(baseUrl);
        url = contextPath.length() > 0 && !url.startsWith(contextPath) ? removeSuffix(contextPath + url) : removeSuffix(url);

        return baseUrl.startsWith(url) || toFlat(baseUrl).startsWith(toFlat(url));
    }


    public boolean isUrlEquals(String url) {
        String baseUrl = getBaseUrl();
        if (StrUtil.isBlank(baseUrl)) {
            return false;
        }

        baseUrl = removeSuffix(baseUrl);
        url = contextPath.length() > 0 && !url.startsWith(contextPath) ? removeSuffix(contextPath + url) : removeSuffix(url);

        return baseUrl.equals(url) || toFlat(baseUrl).equals(toFlat(url));
    }


    private String removeSuffix(String url) {
        int indexOf = url.indexOf(".");
        return indexOf == -1 ? url : url.substring(0, indexOf);
    }


    private String toFlat(String url) {
        return url.replace("/", "-");
    }


}
